package repository

import (
	"context"

	"gitee.com/thewalkers/refactoring-code/model"
	"gitee.com/thewalkers/refactoring-code/model/apperrors"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

// MysqlMailMethodRepository is data/repository implementation
// of service layer EmployeeRepository
type MysqlMailMethodRepository struct {
	DB *sqlx.DB
}

// NewMailMethodRepository is a factory for initializing Employee Repository
func NewMailMethodRepository(db *sqlx.DB) model.MailMethodRepository {
	return &MysqlMailMethodRepository{
		DB: db,
	}
}

func (m *MysqlMailMethodRepository) Create(ctx context.Context, mail *model.MailMethod) error {
	query := `INSERT INTO mail_method(payment_method_id, address) VALUES(?, ?)`

	if _, err := m.DB.Exec(query, mail.PaymentMethodID, mail.Address); err != nil {
		zap.L().Error("repository cound not create a mail method with err: ", zap.Error(err))
		return apperrors.NewInternal()
	}

	return nil
}

func (m *MysqlMailMethodRepository) Update(ctx context.Context, mail *model.MailMethod) error {
	query := `UPDATE mail_method SET address = ? WHERE payment_method_id = ?`

	if _, err := m.DB.Exec(query, mail.Address, mail.PaymentMethodID); err != nil {
		zap.L().Error("repository cound not update a mail method with err: ", zap.Error(err))
		return err
	}

	return nil
}
